/*jslint bitwise: true, eqeqeq: true, immed: true, strict: false, newcap: true, nomen: true, onevar: true, plusplus: true, regexp: false, undef: true, white: true, indent: 4*/
/*global YUI, console, alert, window, document */

/**
 * Standard xhr callback naming convention: methodnameOnSuccess
 */

YUI().use(
    'node',
    'event',
    'json',
    'io-base',
    'io-form',
    'async-queue',
    'anim',
function (Y) {

    YUI.namespace('worldmap').maps = (function () {
        // var declarations
        var appInit;
        // google map instance
        var map;
        // markers indexed by their id
        var markers;
        var markerOptions = new Array();

        // private Methods
        appInit = function () {
            //Event handler
            //Y.on("keyup", Y.worldmap.someSubmodule, '#searchfield');
            if (GBrowserIsCompatible()) {
                Y.log('loading map');
                map = new GMap2(document.getElementById("map"));
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                // TODO: center based on browser location
                map.setCenter(new GLatLng(48.977, 8.581),6);

                var userIcon, storeIcon, eventIcon;
                userIcon = new GIcon(G_DEFAULT_ICON); //standard size and all
                userIcon.image = "/images/marker_user.png";
                storeIcon = new GIcon(G_DEFAULT_ICON);
                storeIcon.image = "/images/marker_store.png";
                eventIcon = new GIcon(G_DEFAULT_ICON);
                eventIcon.image = "/images/marker_event.png";
                markerOptions['user'] = {icon:userIcon};
                markerOptions['store'] = {icon:storeIcon};
                markerOptions['event'] = {icon:eventIcon};
                markerOptions['default'] = {};

                var mgr = new GMarkerManager(map);
                GEvent.addListener(mgr, "changed", YUI.namespace('worldmap').maps.viewportChanged);

                //create markers and add them to the manager
                var _marklist = new Array(); //markermanager does not like non-linear arrays
                markers = new Array();

                for (var j = 0; j < pointData.length; j++) {
                    var marker = createMarker(pointData[j].id, pointData[j].lat, pointData[j].lng, pointData[j].type);
                    markers[pointData[j].id] = marker;
                    _marklist[j] = marker;
                }
                mgr.addMarkers(_marklist,0);
                mgr.refresh();
            }


        };
        createMarker = function(markerid, lat, lng, markertype) {
            var pos = new GLatLng(lat,lng);
            Y.log(markerid + ": "+lat + " " + lng + " " + markertype);
            if (undefined !== markerOptions[markertype]) {
                var marker = new GMarker(pos, markerOptions[markertype]);
            } else {
                var marker = new GMarker(pos, markerOptions['default']);
            }
            marker.myid = markerid;

            var newNode = document.createElement('div');
            newNode.id = "infotext_" + markerid;
            newNode.innerHTML = "<p>loading...</p>";
            Y.one("#infoWindowTexts").appendChild(newNode);
            marker.bindInfoWindow(newNode);
            GEvent.addListener(marker, "infowindowopen", function() {
                GDownloadUrl("./viewport/getDetails?isXMLHttpRequest=1&id=" + markerid, YUI.namespace('worldmap').maps.showDetails);
            });
            return marker;
        }

        // Public methods
        return {
            init: function () {
                Y.on('contentready', appInit, "#content");
            },

            showDetails: function (jsonResponse) {
                try {
                    response = Y.JSON.parse(jsonResponse);
                } catch (e) {
                    Y.log('Could not parse JSON string');
                    response = { status : 'error' };
                }
                document.getElementById("details").innerHTML = response;
            },

            setInfoWindows: function (jsonResponse) {
                var newNode;
                try {
                    response = Y.JSON.parse(jsonResponse);
                } catch (e) {
                    Y.log('Could not parse JSON string');
                    response = { status : 'error' };
                }

                //loop through items
                Y.each(response, function (val, key) {
                    //make node if it does not exists
                    var info = document.getElementById("infotext_" + key); //Y.one("#infotext_"+key) does not work. whatever.
                    if (info != null) {
                        info.innerHTML = val;
                    } else {
                        Y.log("unexpected key "+key);
                    }

                });
            },

            viewportChanged: function(uselessbounds, markerCount) {
                if (markerCount > 0) {
                    var bounds = map.getBounds();
                    GDownloadUrl("./viewport/getBubbleData?isXMLHttpRequest=1&lat_min=" + bounds.getSouthWest().lat() + "&lat_max=" + bounds.getNorthEast().lat() + "&lng_min=" + bounds.getSouthWest().lng() + "&lng_max=" + bounds.getNorthEast().lng(), YUI.namespace('worldmap').maps.setInfoWindows);
                }
            }
        };
    }());

    YUI.namespace('worldmap').maps.init();
});
